﻿using System;
using System.Windows;

namespace SQLDataTransferer
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        #region Constructor(s)

        App()
        {
            this.DispatcherUnhandledException +=
                new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
        }

        #endregion

        #region Overrides

        protected override void OnStartup(StartupEventArgs e)
        {
            SQLDataTransferer.MainWindow window = new SQLDataTransferer.MainWindow();

            // if no resource file created for a specific culture, it will use the default, Resources.resx file
            var vm = new ViewModel.MainWindowViewModel(System.Globalization.CultureInfo.CurrentCulture, this.Dispatcher, window);

            // When the ViewModel asks to be closed, 
            // close the window.
            EventHandler handler = null;
            handler = delegate
            {
                vm.RequestClose -= handler;
                window.Close();
            };
            vm.RequestClose += handler;

            window.DataContext = vm;

            window.Show();
        }

        protected override void OnExit(ExitEventArgs e)
        {
            base.OnExit(e);
        }

        #endregion        

        #region EventHandlers

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                Common.Dialogs.ExceptionDialog.HandleException(e.Exception, this.MainWindow);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Application error!!!");
            }
        }

        #endregion
    }
}
